<template>
  <ContentDetailWrap :title="t('action.add')">
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="submit">
        {{ t('action.save') }}
      </BaseButton>
    </template>

    <el-form :model="form" ref="formRef" label-width="80px">
      <div class="w-full flex justify-between">
        <el-form-item
          :label="t('minescreenFirmwareVersion.firmwareVersion.firmware_download_addr')"
          prop="logistics_voucher"
        >
          <UploadFile
            url="/common/uploadFile"
            upload-file-button-name="点击上传"
            :params="{ directory: 7 }"
            :limit="1"
            :file-type="['bin']"
            list-type="text"
            :show-file-list="true"
            @upload-success-res="handleUploadCallback"
            @handle-remove-file="handleRemoveFile"
          />
        </el-form-item>
      </div>
    </el-form>
  </ContentDetailWrap>
</template>

<script setup lang="ts">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ElMessage, type FormInstance } from 'element-plus'
import { createDataApi } from '@/api/minescreenFirmwareVersion/firmwareVersion'

const { t } = useI18n()
const { push, go } = useRouter()

const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  logistics_voucher: []
})

//上传成功以后回调
const handleUploadCallback = (val: any) => {
  form.value.logistics_voucher.push(val)
}

const handleRemoveFile = (val: any) => {
  if (form.value.logistics_voucher && form.value.logistics_voucher.length) {
    form.value.logistics_voucher = form.value.logistics_voucher.filter(
      (item: Record<string, any>) => item.uploadFile.uid !== val.uid
    )
  }
}

const submit = async () => {
  if (!form.value.logistics_voucher.length) return ElMessage.error('请上传文件')
  try {
    loading.value = true
    const urlList = form.value.logistics_voucher.map((item: Record<string, any>) => item.url)
    const resp = await createDataApi({ firmware_download_addr: urlList[0] || '' })
    if (resp.code === 0) {
      loading.value = false
      ElMessage.success('新增成功')
      push('/minescreenFirmwareVersion/firmwareVersion')
    }
  } catch (e) {
    loading.value = false
  }
}
</script>

<style lang="less" scoped></style>
